package com.walle.ak47.commons.jaxrs;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.ws.rs.core.Response;

import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JaxRSClient 
{

	private static final Logger LOG = LoggerFactory.getLogger(JaxRSClient.class);
	
	WebClient client;
	
	public <T> T post( WebClient client, String url, String header, String requestJson, Class<T> type ) throws Exception 
	{
		Response r = client.post(requestJson);
		if ( r.getStatus() != 200 ) 
		{
			LOG.error( "Request->"+ requestJson );
			LOG.error( "Response->"+ r.readEntity(String.class) );
		}
		
		String jsonResp = r.readEntity(String.class) ;
		JaxrsJson json = new JaxrsJson() ;
		
		T t = null ;
		try
		{
			t = json.readValue(jsonResp, type) ;
		}
		catch( Exception ex )
		{
			throw new Exception("Message json convert Object occur err.\n "
					+ "ResponseJson is "+jsonResp+"; ErrorMessage is "+ex) ;
		}
		return t;
	}
	
	public Response post( String url, String header, String requestJson ) 
	{
		client = WebClient.create( url );
		Response r = client.header("Content-Type", "application/json; charset=UTF-8")
				.header("X-AUTH-HEADER", header)
				.accept("application/json; charset=UTF-8").post(requestJson);

		if ( r.getStatus() != 200 ) 
		{
			LOG.error( "Request->"+ requestJson );
			LOG.error( "Response->"+ r.readEntity(String.class) );
		}
		
//		try 
//		{
//			if (client != null) client.close();
//		} 
//		catch (Exception e) 
//		{
//			LOG.error( "Client close occur err!"+ e );
//		}
		
		return r;
	}
	
	public <T> T post(String url, String path, String token, String requestJson, Class<T> type) throws Exception 
	{
		Response resp = this.post(url+"/"+path, token, requestJson) ;
		String jsonResp = resp.readEntity(String.class) ;
		JaxrsJson json = new JaxrsJson() ;
		
		T t = null ;
		try
		{
			t = json.readValue(jsonResp, type) ;
		}
		catch( Exception ex )
		{
			throw new Exception("Message json convert Object occur err.\n "
					+ "ResponseJson is "+jsonResp+"; ErrorMessage is "+ex) ;
		}
		return t;
	}
	
	public <T> T simplePost(String url, String token, String requestJson, Class<T> type) throws Exception 
	{
		Response resp = this.post(url, token, requestJson) ;
		String jsonResp = resp.readEntity(String.class) ;
		JaxrsJson json = new JaxrsJson() ;
		
		T t = null ;
		try
		{
			t = json.readValue(jsonResp, type) ;
		}
		catch( Exception ex )
		{
			throw new Exception("Message json convert Object occur err.\n "
					+ "ResponseJson is "+jsonResp+"; ErrorMessage is "+ex) ;
		}
		return t;
	}
	
	public String post(String url, String path, String token, String requestJson ) throws Exception 
	{
		Response resp = this.post(url+"/"+path, token, requestJson) ;
		String jsonResp = resp.readEntity(String.class) ;
		return jsonResp;
	}

	
	/**
	 * 直接使用模板进行Jaxrs调用
	 * @param url
	 * @param path
	 * @param token
	 * @param params
	 * @param templateJson
	 * @return
	 */
	public String post( String url, String path, String token, Map<String,String> params, String templateJson )
	{
		if ( StringUtils.isBlank(url) || StringUtils.isBlank(path) || StringUtils.isBlank(token) )
		{
			LOG.error( "请求发送出现失败(参数错误), 参数信息:url={},path={},token={}",new Object[]{url, path, token} );
			return null ;
		}
		
		String result ;
		String paramJson = setParams(params, templateJson) ;
		try
		{
			JaxRSClient jaxRSClient = new JaxRSClient() ;
			result =  jaxRSClient.post( url, path,  token, paramJson ) ;
		}
		catch ( Exception ex )
		{
			LOG.error( "err=>发送请求出现异常,reqJson:{}, errMsg:{}", paramJson, ex );
			return null; 
		}
		
		return result;
	}
	private String setParams( Map<String,String> params, String templateJson)
	{
		String json = templateJson ;
		Iterator<Map.Entry<String, String>> iter = params.entrySet().iterator() ;
		while ( iter.hasNext() )
		{
			Entry<String, String> entry = iter.next() ;
			json = StringUtils.replace(json, entry.getKey(), entry.getValue()) ;
		}
		return json ;
	}
	
}
